<template>
  <div id="userPage" @click="showResult = false">
    <HeadNav
      type="application"
      ref="head"
      :show="1"
      @publisherChange="publisherChange()"
    ></HeadNav>
    <div class="wd-1220">
      <div class="clearfix">
        <div class="float-left">
          <SlideNav type="application" sort="authors"></SlideNav>
        </div>
        <div class="float-right">
          <div class="main-container" v-if="pagePower == 1">
            <div class="model-container">
              <div class="model-bg" style="min-height: 660px">
                <div class="section-title">作者信息</div>
                <div class="container" style="padding-bottom: 20px">
                  <div class="option">
                    <span class="lable top">作者头像</span>
                    <div class="normal">
                      <img
                        :src="authorInfo.photo"
                        alt=""
                        style="width: 80px; height: 80px"
                        v-if="authorInfo.photo"
                      />
                      <span
                        v-else
                        class="no-pic"
                        style="
                          min-width: 80px;
                          min-height: 80px;
                          border-radius: 10px;
                        "
                      ></span>
                    </div>
                    <div
                      class="uploadPackage"
                      style="
                        display: inline-block;
                        vertical-align: top;
                        margin-left: 5px;
                        width: 100px;
                        height: 32px;
                        overflow: hidden;
                      "
                    >
                      <a-upload
                        name="file"
                        accept=".png,.jpg,.jpeg"
                        :customRequest="handleChange"
                      >
                        <a-button> <a-icon type="upload" /> 上传图片 </a-button>
                      </a-upload>
                    </div>
                  </div>
                  <div class="option">
                    <span class="lable">*作者名称</span>
                    <div class="normal" style="width: 460px">
                      <a-input
                        placeholder="输入作者名称"
                        v-model="authorInfo.name"
                      />
                    </div>
                  </div>
                  <div class="option">
                    <span class="lable">国家</span>
                    <div class="normal">
                      <a-select
                        show-search
                        placeholder="请选择国家"
                        option-filter-prop="children"
                        style="width: 220px"
                        :filter-option="onSearch"
                        v-model="authorInfo.country_code"
                        @change="selectOpt"
                      >
                        <a-select-option
                          v-for="(citem, cindex) in countryList"
                          :key="cindex"
                          :value="citem.code"
                        >
                          {{ citem.country }}
                        </a-select-option>
                      </a-select>
                    </div>
                  </div>
                  <div class="option">
                    <span class="lable">作者类型</span>
                    <div class="normal">
                      <a-select
                        placeholder="请选择作者类型"
                        option-filter-prop="children"
                        style="width: 220px"
                        :filter-option="onSearch"
                        v-model="authorInfo.author_type"
                      >
                        <a-select-option
                          v-for="(citem, cindex) in authorTypeList"
                          :key="cindex"
                          :value="citem.type"
                        >
                          {{ citem.name }}
                        </a-select-option>
                      </a-select>
                    </div>
                  </div>
                  <div class="option">
                    <span class="lable">生日</span>
                    <div class="normal" style="width: 460px">
                      <a-date-picker
                        @change="onChangeBirth"
                        inputReadOnly
                        v-model="authorInfo.birthday"
                      />
                    </div>
                  </div>
                  <div class="option">
                    <span class="lable">逝世</span>
                    <div class="normal" style="width: 460px">
                      <a-date-picker
                        @change="onChangeDeath"
                        inputReadOnly
                        v-model="authorInfo.death_date"
                      />
                    </div>
                  </div>
                  <div class="option">
                    <span class="lable top">作者介绍</span>
                    <div class="normal" style="width: 800px">
                      <a-textarea
                        placeholder="请输入作者介绍"
                        v-model="authorInfo.description"
                        style="height: 180px"
                      />
                    </div>
                  </div>
                  <div class="option">
                    <span class="lable">微博链接</span>
                    <div class="normal" style="width: 460px">
                      <a-input
                        placeholder="输入微博链接"
                        v-model="authorInfo.weibo.link"
                      />
                    </div>
                  </div>
                  <div class="option">
                    <span class="lable">抖音链接</span>
                    <div class="normal" style="width: 460px">
                      <a-input
                        placeholder="输入抖音链接"
                        v-model="authorInfo.douyin.link"
                      />
                    </div>
                  </div>
                  <div class="option">
                    <span class="lable">是否加入排行</span>
                    <div class="normal">
                      <a-switch v-model="isRank" />
                    </div>
                  </div>
                  <div class="option" style="margin-top: 50px">
                    <span class="lable"></span>
                    <div class="normal">
                      <a-button type="primary" @click="save">保存修改</a-button>
                      <a-button
                        type="default"
                        style="margin-left: 5px"
                        @click="$router.go(-1)"
                        >放弃</a-button
                      >
                      <a-button
                        type="default"
                        style="margin-left: 5px"
                        @click="merge"
                        >合并作者</a-button
                      >
                      <a-button
                        type="default"
                        style="margin-left: 5px"
                        @click="
                          authorModal = true;
                          authorInput = '';
                          dataSourceAuthor = [];
                          newAuthorID = 0;
                        "
                        >调整作品</a-button
                      >
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="main-container" v-else>
            <div class="model-container">
              <div
                class="model-bg"
                style="
                  min-height: 660px;
                  padding-bottom: 75px;
                  position: relative;
                "
              >
                <PageNoPower></PageNoPower>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 作者合并 -->
    <a-modal
      v-model="addOrganize"
      width="600px"
      title="作者合并"
      on-ok="handleOk"
    >
      <template slot="footer">
        <!-- <a-button key="back" @click="handleCancel">取消</a-button> -->
        <a-button key="submit" type="primary" @click="handleOk">合并</a-button>
      </template>
      <div class="popup" style="height: 215px" @click="showResult = false">
        <span>选择作者</span>
        <div style="width: 310px; display: inline-block; position: relative">
          <a-input
            placeholder="搜索作者名称"
            @input="searchAuthor"
            @focus="searchAuthor"
            @click.stop="inputClick"
            v-model="inputAuthor"
          >
          </a-input>
          <div class="search-result" v-if="showResult">
            <div class="list" v-if="dataSource.length > 0">
              <div
                class="result-content"
                v-for="(item, index) in dataSource"
                :key="index"
                @click.stop="onSelect(item, index)"
              >
                <span class="result-title" :title="item.name"
                  >{{ item.name }}（{{ item.author_id }}）</span
                >
              </div>
            </div>
            <div class="no-result" v-if="dataSource.length == 0 && showAbout">
              没有相关作者
            </div>
            <div
              style="text-align: center; margin-top: 50px"
              v-if="searchLoading"
            >
              <a-spin tip></a-spin>
            </div>
          </div>
        </div>
      </div>
    </a-modal>
    <!-- 调整作品--选择作者弹窗 -->
    <a-modal
      v-model="authorModal"
      width="600px"
      title="调整作品列表"
      destroyOnClose
      on-ok="handleOk"
    >
      <template slot="footer">
        <a-button key="submit" type="primary" @click="authorNext"
          >下一步</a-button
        >
      </template>
      <div class="popup" @click="showResult = false">
        <div class="clearfix">
          <div class="float-left" style="line-height: 32px">原作者</div>
          <div class="float-left" style="width: 280px; margin-left: 10px">
            <a-input v-model="authorName" disabled />
          </div>
        </div>
        <div class="clearfix" style="margin-top: 10px">
          <div class="float-left" style="line-height: 32px">新作者</div>
          <div class="float-left" style="margin-left: 10px">
            <div
              style="width: 280px; display: inline-block; position: relative"
            >
              <a-input
                placeholder="搜索作者名称"
                @input="onSearchAuthor"
                @focus="onSearchAuthor"
                @click.stop="inputClick"
                v-model="authorInput"
              >
              </a-input>
              <div class="search-result" v-if="showResult">
                <div class="list" v-if="dataSourceAuthor.length > 0">
                  <div
                    class="result-content"
                    v-for="(item, index) in dataSourceAuthor"
                    :key="index"
                    @click.stop="selectedAuthor(item, index)"
                  >
                    <span class="result-title" :title="item.name"
                      >{{ item.name }}（{{ item.author_id }}）</span
                    >
                  </div>
                </div>
                <div
                  class="no-result"
                  v-if="dataSourceAuthor.length == 0 && showAbout"
                >
                  没有相关作者
                </div>
                <div
                  style="text-align: center; margin-top: 50px"
                  v-if="searchLoading"
                >
                  <a-spin tip></a-spin>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div style="height: 150px"></div>
      </div>
    </a-modal>
    <!-- 调整作品--作品弹窗 -->
    <a-modal
      v-model="adjustGoods"
      width="650px"
      title="调整作品列表"
      destroyOnClose
      on-ok="handleOk"
    >
      <template slot="footer">
        <a-button key="submit" type="primary" @click="adjustCompelete"
          >完成</a-button
        >
      </template>
      <div class="popup">
        <a-transfer
          :data-source="mockData"
          show-search
          :list-style="{
            width: '280px',
            height: '440px',
          }"
          :target-keys="targetKeys"
          :render="(item) => `${item.title}`"
          :titles="['原作者：' + authorName, '新作者：' + lastAuthor]"
          @change="authorHandleChange"
        >
          <a-button
            slot="footer"
            slot-scope="props"
            size="small"
            style="float: right; margin: 5px"
            @click="getMock"
          >
            刷新
          </a-button>
          <span slot="notFoundContent"> 暂无数据 </span>
        </a-transfer>
      </div>
    </a-modal>
    <Loading ref="load" :show="1" :isLoading="isLoading"></Loading>
  </div>
</template>
<style scoped lang="scss" src="@/style/scss/pages/user/information.scss"></style>
<script>
import {
  INDUSTRY_AUTHOR_INFO,
  INDUSTRY_AUTHOR_SEARCH,
  INDUSTRY_AUTHOR_EDIT,
  INDUSTRY_AUTHOR_MERGE,
  INDUSTRY_AUTHOR_GOODS,
  INDUSTRY_AUTHOR_GOODS_CHANGE,
} from "../../apis/industry.js";
import { COMMON_COUNTRY } from "../../apis/common.js";
export default {
  data() {
    return {
      pagePower: 1,
      authorId: 0,
      isLoading: true,
      pic: "",
      authorInfo: {
        douyin: {
          link: "",
        },
        weibo: {
          link: "",
        },
      },
      isRank: false,
      countryList: [],
      choose: false,
      inputVal: "",
      inputAuthor: "",
      addOrganize: false,
      chooseId: 0,
      dataSource: [],
      showResult: false,
      searchLoading: false,
      showAbout: false,
      // 调整作者
      authorName: "",
      authorModal: false,
      dataSourceAuthor: [],
      lastAuthor: "",
      lastAuthorLabel: "",
      newAuthorID: 0,
      authorInput: "",
      adjustGoods: false,
      goodsList: [],
      mockData: [],
      targetKeys: [],
      authorTypeList:[
        {name:"当代作家",type:1},
        {name:"公版书作家",type:2},
        {name:"译者",type:3},
        {name:"编者",type:4},
        {name:"工作室",type:5},
      ]
    };
  },
  mounted() {
    this.authorId = this.$route.query.author_id;
    this.pagePower = this.$refs.head.accountInfo.type;
    if (this.pagePower == 1) {
      this.getCountry();
      this.getData();
    } else {
      this.isLoading = false;
    }
  },
  methods: {
    // 获取作者信息
    async getData() {
      var tStamp = this.$getTimeStamp();
      let data = {
        author_id: this.authorId,
        organization_id: this.$refs.head.publishInfo.organization_id,
        timestamp: tStamp,
      };
      data.sign = this.$getSign(data);
      let res = await INDUSTRY_AUTHOR_INFO(data);
      if (res.code == 0) {
        // this.pagePower = true;
        this.authorInfo = res.data;
        this.authorName = res.data.name;
        this.pic = res.data.photo;
        this.authorInfo.birthday = this.authorInfo.birthday.replace(
          /年|月/g,
          "-"
        );
        this.authorInfo.birthday = this.authorInfo.birthday.replace(/日/g, "");
        this.authorInfo.death_date = this.authorInfo.death_date.replace(
          /年|月/g,
          "-"
        );
        this.authorInfo.death_date = this.authorInfo.death_date.replace(
          /日/g,
          ""
        );
        this.authorInfo.country_code = this.authorInfo.country_code?this.authorInfo.country_code:undefined;
        this.authorInfo.author_type = this.authorInfo.author_type?this.authorInfo.author_type:undefined;
        this.authorInfo.description = this.authorInfo.description?this.authorInfo.description:'';
        this.isRank = this.authorInfo.is_rank == 1?true:false;
        this.$nextTick(() => {
          this.isLoading = false;
        });
      } else {
        this.isLoading = false;
        if (res.code == 1009) {
          // this.pagePower = false;
        } else {
          this.$refs.head.globalTip(1, res.message, res.code);
        }
      }
    },
    // 获取国家列表
    async getCountry(file) {
      var tStamp = this.$getTimeStamp();
      let data = {
        timestamp: tStamp,
      };
      data.sign = this.$getSign(data);
      let res = await COMMON_COUNTRY(data);
      if (res.code == 0) {
        this.countryList = [];
        this.countryList = res.data;
      } else {
        this.isLoading = false;
        this.$refs.head.globalTip(1, res.message, res.code);
      }
    },
    async upload(_content) {
      var tStamp = this.$getTimeStamp();
      let data = {
        // aaa: _content,
        timestamp: tStamp,
      };
      data.sign = this.$getSign(data);
      let formData = new FormData(),
        _this = this;
      formData.append("file", _content);
      formData.append("timestamp", tStamp);
      formData.append("sign", data.sign);
      this.$axios({
        url: _this.$baseUrl + "/common/upload",
        method: "post",
        data: formData,
      }).then((res) => {
        if (res.data.code == 0) {
          _this.$refs.head.globalTip(2, "上传成功", 0);
          _this.authorInfo.photo = res.data.data.file;
        } else {
          _this.$refs.head.globalTip(1, res.data.message, res.data.code);
        }
      });
    },
    // 保存
    async saveAuthor() {
      var tStamp = this.$getTimeStamp();
      let data = {
        author_id: this.authorId,
        pic: this.authorInfo.photo,
        author_name: this.authorInfo.name,
        country_code: this.authorInfo.country_code?this.authorInfo.country_code:'',
        birth_date: this.authorInfo.birthday,
        death_date: this.authorInfo.death_date,
        description: this.authorInfo.description?this.authorInfo.description:'',
        weibo_link: this.authorInfo.weibo.link,
        douyin_link: this.authorInfo.douyin.link,
        is_rank: this.isRank?1:0,
        author_type: this.authorInfo.author_type?this.authorInfo.author_type:0,
        timestamp: tStamp,
      };
      data.sign = this.$getSign(data);
      let res = await INDUSTRY_AUTHOR_EDIT(data);
      if (res.code == 0) {
        this.$refs.head.globalTip(2, "保存成功！", 0);
        let _this = this;
        setTimeout(() => {
          // _this.$router.go(-1);
        }, 1000);
      } else {
        this.$refs.head.globalTip(1, res.message, res.code);
      }
    },
    // 合并作者
    async mergeAuthor() {
      var tStamp = this.$getTimeStamp();
      let data = {
        author_id: this.authorId,
        target_author_id: this.chooseId,
        timestamp: tStamp,
      };
      data.sign = this.$getSign(data);
      let res = await INDUSTRY_AUTHOR_MERGE(data);
      if (res.code == 0) {
        this.$refs.head.globalTip(2, "合并成功！", 0);
        let _this = this;
        setTimeout(() => {
          _this.$router.go(-1);
        }, 1000);
      } else {
        this.$refs.head.globalTip(1, res.message, res.code);
      }
    },
    // 搜索作者列表
    async getAuthorData(type, val) {
      var tStamp = this.$getTimeStamp();
      let data = {
        search: val,
        timestamp: tStamp,
      };
      data.sign = this.$getSign(data);
      let res = await INDUSTRY_AUTHOR_SEARCH(data);
      if (res.code == 0) {
        if (type == 1) {
          this.dataSource = [];
          if(this.inputAuthor.length > 0){
            this.dataSource = res.data;
          }
          this.searchLoading = false;
          this.showAbout = true;
        } else {
          this.dataSourceAuthor = [];
          if(this.authorInput.length > 0){
            res.data.map((v, k) => {
              v.label = v.name + "（" + v.author_id + "）";
              this.dataSourceAuthor.push(v);
            });
          }
          this.searchLoading = false;
          this.showAbout = true;
        }
      } else {
        this.searchLoading = false;
        this.$refs.head.globalTip(1, res.message, res.code);
      }
    },
    // 获取作者作品列表
    async getAuthorList() {
      var tStamp = this.$getTimeStamp();
      let data = {
        author_id: this.authorId,
        organization_id: this.$refs.head.publishInfo.organization_id,
        page: 1,
        page_size: 100000,
        timestamp: tStamp,
      };
      data.sign = this.$getSign(data);
      let res = await INDUSTRY_AUTHOR_GOODS(data);
      if (res.code == 0) {
        this.mockData = [];
        this.goodsList = [];
        res.data.list.map((value, key) => {
          let _obj = {
            key: value.goods_id.toString(),
            title: value.name,
            description: value.publisher,
          };
          this.goodsList.push(_obj);
          this.mockData.push(_obj);
        });
        this.$nextTick(() => {
          this.isLoading = false;
        });
      } else {
        this.isLoading = false;
        if (res.code == 1009) {
          this.pagePower = false;
        } else {
          this.$refs.head.globalTip(1, res.message, res.code);
        }
      }
    },
    // 修改作者作品
    async authorGoodsChange() {
      var tStamp = this.$getTimeStamp();
      let data = {
        del_author_id: this.authorId,
        add_author_id: this.newAuthorID,
        goods_ids: this.targetKeys.join(","),
        timestamp: tStamp,
      };
      data.sign = this.$getSign(data);
      let res = await INDUSTRY_AUTHOR_GOODS_CHANGE(data);
      if (res.code == 0) {
        this.$refs.head.globalTip(2, "修改成功！", 0);
        this.adjustGoods = false;
      } else {
        this.$refs.head.globalTip(1, res.message, res.code);
      }
    },
    // 上传图片
    handleChange(info) {
      this.upload(info.file);
    },
    onSearch(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    selectOpt(value) {
      this.authorInfo.country_code = value;
    },
    onChangeBirth(date, dateString) {
      this.authorInfo.birthday = dateString;
    },
    onChangeDeath(date, dateString) {
      this.authorInfo.death_date = dateString;
    },
    // 保存
    save() {
      if (this.authorInfo.name.length == 0) {
        this.$refs.head.globalTip(1, "作者名称不能为空！", 0);
        return;
      }
      this.saveAuthor();
    },
    // 合并
    handleOk() {
      this.showResult = false;
      if (this.chooseId == 0) {
        this.$refs.head.globalTip(1, "请选择作者！", 0);
        return;
      }
      var _this = this;
      this.$confirm({
        title: "确认合并",
        content:
          "确认将“" +
          _this.authorInfo.name +
          "”合并至作者“" +
          _this.inputAuthor +
          "”，合并后无法撤销。合并后，“" +
          _this.authorInfo.name +
          "”将被删除，其下的所有品种将转移至“" +
          _this.inputAuthor +
          "”，作者信息以“" +
          _this.inputAuthor +
          "”为准。",
        okText: "确认",
        cancelText: "取消",
        okType: "primary",
        onOk() {
          _this.mergeAuthor();
        },
        onCancel() {},
      });
    },
    merge() {
      this.addOrganize = true;
      this.chooseId = 0;
      this.dataSource = [];
      this.inputAuthor = "";
    },
    searchAuthor() {
      if (this.inputAuthor.length > 0) {
        this.chooseId = 0;
        this.dataSource = [];
        this.showResult = true;
        this.searchLoading = true;
        this.showAbout = false;
        this.getAuthorData(1, this.inputAuthor);
      } else {
        this.dataSource = [];
      }
    },
    onSelect(item, index) {
      this.chooseId = item.author_id;
      this.inputAuthor = item.name;
      this.showResult = false;
    },
    // 作者作品调整完成
    adjustCompelete() {
      if (this.targetKeys.length == 0) {
        this.$refs.head.globalTip(1, "请选择需要调整的作品！", 0);
        return;
      }
      let _this = this;
      this.$confirm({
        title: "确认调整作品列表",
        content:
          "确认将" +
          _this.targetKeys.length +
          "个品种从原作者“" +
          _this.authorName +
          "”转移至新作者“" +
          _this.lastAuthor +
          "”，转移后无法撤销。",
        okText: "确认",
        cancelText: "取消",
        okType: "primary",
        onOk() {
          _this.authorGoodsChange();
        },
        onCancel() {},
      });
    },
    // 作者合并下一步
    authorNext() {
      this.showResult = false;
      if (this.newAuthorID == 0) {
        this.$refs.head.globalTip(1, "请选择新作者！", 0);
        return;
      }
      this.authorModal = false;
      this.targetKeys = [];
      this.adjustGoods = true;
      this.isLoading = true;
      this.getAuthorList();
    },
    // 穿梭框变化
    authorHandleChange(targetKeys, direction, moveKeys) {
      this.targetKeys = targetKeys;
    },
    // 穿梭框刷新
    getMock() {},
    // 作者
    onSearchAuthor() {
      if (this.authorInput.length > 0) {
        this.dataSourceAuthor = [];
        this.showResult = true;
        this.searchLoading = true;
        this.showAbout = false;
        this.getAuthorData(2, this.authorInput);
      } else {
        this.dataSourceAuthor = [];
      }
    },
    // 选中作者
    selectedAuthor(item,index) {
      this.authorInput = item.name;
      this.newAuthorID = item.author_id;
      this.lastAuthor = item.name;
      this.lastAuthorLabel = item.label;
      this.showResult = false;
    },
    inputClick() {},
    publisherChange() {
      this.pagePower = this.$refs.head.accountInfo.type;
    },
  },
};
</script>
